import React, { useState } from "react";
import ErrorBoundary from "./common/ErrorBoundary";

const FormSubmitter: React.FC = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    try {
      console.log("提交表单...", { name, email });
      // 模拟 API 请求
      const response = await fetch("https://api.example.com/submit", {
        method: "POST",
        body: JSON.stringify({ name, email }),
      });

      if (!response.ok) {
        throw new Error("服务器回应有误");
      }

      const data = await response.json();
      console.log("表单提交成功:", data);
      // 处理成功回应...
    } catch (err) {
      console.error("表单提交错误:", err);
      setError("哎呀！表单提交失败了，请稍后再试。");
    }
  };

  return (
    <ErrorBoundary fallback={<div>哎呀！出了一些问题。请刷新页面试试。</div>}>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="姓名"
          required
        />
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="电子邮件"
          required
        />
        <button type="submit">提交</button>
        {error && <div style={{ color: "red" }}>{error}</div>}
      </form>
    </ErrorBoundary>
  );
};

export default FormSubmitter;
